// pages/search/search.js
import request from '../../utils/requests'
let isSend = false //用于函数节流，实现的业务为当用户缓慢输入的时候就发送，当用户快速输入的时候就在单位时间后在发送
Page({

    /**
     * 页面的初始数据
     */
    data: {
        searchList:[],
        hotList: [],
        searchContent:' ',
        placeholderContent: ' ',
        historyList: [],
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.getplaceholderdata();
        this.gethotList();
        this.setData({
            historyList : wx.getStorageSync('history')
        })
    },

    async getplaceholderdata(){
        let result = await request('/search/default');
        if(result.code === 200){
            this.setData({
                placeholderContent:result.data.showKeyword
            })
        }
    },

    deleteSearchHistory(){
        wx.setStorageSync('history', [])
    },

    handleInputChange(event){
        this.setData({
            searchContent:event.detail.value.trim()
        })

        if(isSend){
            return ;
        }
        isSend = true;
        this.sendsearch(event.detail.value.trim(),10);  //发送搜索信息
        setTimeout(() => {
            isSend = false;  //设置定时器每个1000ms把isSsend置为false，意味着可以发送请求
        },900);
    },

    clearSearchContent(){
        this.setData({
            searchList:[],
            searchContent: ' '
        })
    },

    async sendsearch(keywords,limit){
        let result = await request('/search',{keywords:keywords,limit:limit})
        if(result.code === 200){
            let hislis = this.data.historyList;
            hislis.unshift(this.data.searchContent);
            this.setData({
                searchList:result.result.songs,
                historyList:hislis
            })
        }
    },

    async gethotList(){
        let result = await request('/search/hot/detail')
        if(result.code === 200){
            this.setData({
                hotList : result.data
            })
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        let data = this.data.searchContent
        if(!(data === ' ' || data === null)){
            let historyList = this.data.historyList
            historyList.unshift(data);
            wx.setStorageSync('history', historyList)
        }
        // this.setData({
        //     historyList
        // })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})